package org.budo.support.java.security.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author lmw
 */
public class DigestUtil {
    public static String md5Hex(byte[] input) {
        if (null == input) {
            return null;
        }

        return org.apache.commons.codec.digest.DigestUtils.md5Hex(input);
    }

    public static String md5Hex(String input) {
        if (null == input) {
            return null;
        }

        return org.apache.commons.codec.digest.DigestUtils.md5Hex(input);
    }

    public static String md5(String input) {
        MessageDigest md = getMessageDigestInstance("md5");
        byte[] hashBytes = md.digest(input.getBytes());
        return fixedHexString(hashBytes);
    }

    public static MessageDigest getMessageDigestInstance(String algorithm) {
        try {
            return MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static String fixedHexString(byte[] hashBytes) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < hashBytes.length; i++) {
            String hex16 = Integer.toString((hashBytes[i] & 0xff) + 0x100, 16);
            stringBuffer.append(hex16.substring(1));
        }

        return stringBuffer.toString();
    }

    private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    public static String sha1(String input) {
        try {
            MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
            sha1.reset();
            sha1.update(input.getBytes("UTF-8"));
            return bytesToHex(sha1.digest());
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    private static String bytesToHex(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        // 把密文转换成十六进制的字符串形式
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }
}